package cn.turboinfo.fuyang.api.domain.common.handler.rule.impl;

import cn.turboinfo.fuyang.api.domain.common.handler.rule.IRuleGroupObjectFilter;
import cn.turboinfo.fuyang.api.entity.common.enumeration.rule.RuleControlType;
import cn.turboinfo.fuyang.api.entity.common.enumeration.rule.control.PagingRequestControl;
import cn.turboinfo.fuyang.api.entity.common.pojo.rule.RuleGroup;
import cn.turboinfo.fuyang.api.entity.common.pojo.rule.RuleItem;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QPage;
import net.sunshow.toolkit.core.qbean.api.request.QSort;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Component
public class PagingRequestRuleGroupFilter implements IRuleGroupObjectFilter {

    @Override
    public RuleControlType getType() {
        return RuleControlType.PAGING_REQUEST;
    }

    @Override
    public Object filterObject(Object element, RuleGroup ruleGroup, Object controlObject) {
        if (element != null && !(element instanceof QPage)) {
            log.error("不支持的过滤对象类型, type={}", element.getClass());
            return element;
        }

        QPage requestPage = (QPage) element;
        if (requestPage == null) {
            requestPage = QPage.newInstance();
        }

        List<RuleItem> itemList = ruleGroup.getItemList();

        for (RuleItem ruleItem : itemList) {
            try {
                PagingRequestControl control = PagingRequestControl.get(ruleItem.getLabelValue());

                switch (control) {
                    case PageIndex:
                        requestPage.setPageIndex(Integer.parseInt(ruleItem.getControlValue()));
                        break;
                    case PageSize:
                        requestPage.setPageSize(Integer.parseInt(ruleItem.getControlValue()));
                        break;
                    case Sort:
                        // 排序
                        // 排序规则格式 fieldA>|fieldB<|fieldC  大于号表示降序 小于号表示升序 默认升序可省略 多个字段用 | 隔开
                        String[] sortFields = StringUtils.split(ruleItem.getControlValue(), "|");
                        for (String sortField : sortFields) {
                            if (sortField.endsWith(">")) {
                                requestPage.addOrder(StringUtils.substringBefore(sortField, ">"), QSort.Order.DESC);
                            } else {
                                requestPage.addOrder(StringUtils.substringBefore(sortField, "<"), QSort.Order.ASC);
                            }
                        }
                        break;
                }
            } catch (Exception e) {
                log.error("处理规则条目出错", e);
            }
        }

        return requestPage;
    }
}
